package com.jhh.pay.weishenma.service.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.jhh.pay.weishenma.security.Base;
import com.jhh.pay.weishenma.service.WsmService;
import com.jhh.pay.weishenma.util.HttpClientUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Component
public class WsmServiceImpl implements WsmService {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private Base base;

	@Autowired
	private HttpClientUtil httpClientUtil;

	@Override
	public void sendOrder(List<JSONObject> orderList) {
		for (JSONObject order : orderList) {
			sendOrder(order);
		}
	}

	@Override
	public String sendOrder(JSONObject order) {
		// JSONObject jo = new JSONObject();
		Map<String, Object> map = getDefaultDataMap();
		for (Object key : order.keySet()) {
			base.setOrderVals(map, key.toString(), order.get(key));
		}
		try {
			base.fillOrder(order, map);
		} catch (Exception e) {
			e.printStackTrace();
		}

		String orderData = JSONObject.fromObject(map).toString();
		logger.info(orderData);
		// 发起请求
		String result = post(Base.sendOrderUrl, orderData);
		String errorMsg = "";
		if (result.equals("error")) {
			errorMsg = "握手成功，订单没有进入微神马程序中，订单基础字段缺失。" + "建议仔细查看订单并补全缺失的字段，并触发重发订单机制";
		} else if (result.equals("success")) {
			errorMsg = "握手成功，订单进入wsm程序中，并开始校验，请在回调接口中查看" + "微神马返回的回调信息。" + "中间会有一小段时间，请等待。"
					+ "如果长时间没有收到回调，可以调用订单查询接口，查看订单目前状态。";
		}
		System.out.println(errorMsg);
		logger.info(errorMsg);
		return result;
	}

	@Override
	public String checkOrderQuery(String orderId) {
		System.out.println("==============查询订单===============");
		List<String> listData = new ArrayList<>();
		listData.add(orderId); // shddh
		JSONArray json = JSONArray.fromObject(listData);
		String shddhData = json.toString();
		String mid = Integer.toString(base.getMid());
		shddhData = shddhData + "&mid=" + mid;
		String orderQueryResault = postQuery(Base.checkOrderUrl, shddhData);

		System.out.println("--------------------------");
		System.out.println(orderQueryResault);
		System.out.println("--------------------------");

		JSONArray orderQueryList = JSONArray.fromObject(orderQueryResault); // 首先把字符串转成 JSONArray 对象
		if (orderQueryList.size() > 0) {
			for (int i = 0; i < orderQueryList.size(); i++) {

				JSONObject job = orderQueryList.getJSONObject(i); // 遍历 jsonarray 数组，把每一个对象转成 json 对象
				String state = job.get("state").toString();
				String errorcode = job.get("errorcode").toString();
				if (state.equals("error")) {
					// 频率将额外可重新查询
					if (errorcode.equals("1028")) {
						System.out.println("订单查询过频，限制每5秒查询一次，每次可查询多个订单号，稍后再继续查询。shddh：" + job.get("shddh"));
					}
					// 订单在处理中，可稍后再重新查询
					else if (errorcode.equals("1023")) {
						System.out.println("订单处理中，稍后再继续查询。shddh：" + job.get("shddh"));
					}
					// 订单不存在
					else if (errorcode.equals("1022")) {
						System.out.println("订单不存在。shddh：" + job.get("shddh"));
					}
					// 其他状况，订单出现问题，对应code码查看错误原因
					else {
						System.out.println("订单出错，不需要再次查询了，查了也是同样的结果，检查错误信息修改订单吧。shddh：" + job.get("shddh"));
					}
				}
			}
		}
		return orderQueryResault;
	}

	private String postQuery(String path, String post) {
		String line1 = null;
		HttpsURLConnection urlCon = null;
		try {
			urlCon = httpClientUtil.getConnection(path);
			urlCon.setDoInput(true);
			urlCon.setDoOutput(true);
			urlCon.setRequestMethod("POST");
			urlCon.setRequestProperty("Content-Length",
					String.valueOf(post.getBytes().length));
			urlCon.setUseCaches(false);
			post = "data=" + post;
			byte[] bytes = post.getBytes("utf-8");
			urlCon.getOutputStream().write(bytes);
			urlCon.getOutputStream().flush();
			urlCon.getOutputStream().close();
			InputStream inputStream = urlCon.getInputStream();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					inputStream));
			String line;

			while ((line = in.readLine()) != null) {
				line1 = line;
			}

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return line1;
	}

	/**
	 * 发送请求.
	 * 
	 * @param httpsUrl
	 *            请求的地址
	 * @param xmlStr
	 *            请求的数据
	 */
	private String post(String path, String post) {
		String line1 = null;
		HttpsURLConnection urlCon = null;
		try {
			urlCon = httpClientUtil.getConnection(path);
			urlCon.setDoInput(true);
			urlCon.setDoOutput(true);
			urlCon.setRequestMethod("POST");
			urlCon.setRequestProperty("Content-Length", String.valueOf(post.getBytes().length));
			urlCon.setUseCaches(false);
			post = "data=" + URLEncoder.encode(post, "utf-8");
			byte[] bytes = post.getBytes("utf-8");
			urlCon.getOutputStream().write(bytes);
			urlCon.getOutputStream().flush();
			urlCon.getOutputStream().close();
			InputStream inputStream = urlCon.getInputStream();
			// int available = inputStream.available();
			BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
			String line;

			while ((line = in.readLine()) != null) {
				line1 = line;
			}

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return line1;
	}

	private Map<String, Object> getDefaultDataMap() {
		Map<String, Object> map = new LinkedHashMap<>();
		map.put("mid", "");
		map.put("shmyc", "");
		map.put("shddh", "");
		map.put("xm", "");
		map.put("sfzh", "");
		map.put("sjh", "");
		map.put("sflx", "");
		map.put("sfzzpdz", "");
		map.put("dzxx", "");
		map.put("hyzk", "");
		map.put("jkzk", "");
		map.put("zgxl", "");
		map.put("yx", "");
		map.put("zy", "");
		map.put("gsmc", "");
		map.put("gsdh", "");
		map.put("lxrxm1", "");
		map.put("lxrdh1", "");
		map.put("lxrgx1", "");
		map.put("lxrxm2", "");
		map.put("lxrdh2", "");
		map.put("lxrgx2", "");
		map.put("dkyt", "");
		map.put("yhklx", "");
		map.put("kh", "");
		map.put("khh", "");
		map.put("ylsjh", "");
		map.put("sqje", "");
		map.put("cpm", "");
		map.put("cpmx", "");
		map.put("qx", "");
		map.put("jjfwxyqysj", "");
		map.put("jjfwxyckdz", "");
		map.put("casqxyqysj", "");
		map.put("casqxyckdz", "");
		map.put("dkxyqysj", "");
		map.put("dkxyckdz", "");
		map.put("qyszsheng", "");
		map.put("qyszshi", "");
		map.put("ts", "");
		map.put("fkxx", "");
		map.put("on_line", "");
		map.put("timestamp", "");
		map.put("sign", "");
		map.put("zfmx", "");
		map.put("sfdf", "");
		map.put("sfdk", "");
		map.put("zfje", "");
		map.put("ktje", "");
		map.put("dgkhh", "");
		map.put("dggsmc", "");
		map.put("dgkhhbh", "");
		map.put("dgkhhkh", "");
		map.put("dgkhhsheng", "");
		map.put("dgkhhshi", "");
		map.put("dsfzfjybh", "");
		return map;
	}

}
